package api

import (
	"github.com/EDDYCJY/go-gin-app/models"
	"github.com/EDDYCJY/go-gin-app/pkg/e"
	"github.com/EDDYCJY/go-gin-app/pkg/response"
	"github.com/EDDYCJY/go-gin-app/pkg/util"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
)

type auth struct {
	UserName string `valid:"Required;MaxSize(50)"`
	Password string `valid:"Required; MaxSize(50)"`
}
/**
获取token
 */
func GetToken(c *gin.Context)  {
	userName := c.Query("user_name")
	password := c.Query("password")
	valid := validation.Validation{}
	a := auth{UserName: userName,Password: password}
	ok,_ := valid.Valid(&a)
	data := make(map[string]interface{})
	code := e.INVALID_PARAMS
	msg := ""
	if ok {
		userInfo := models.CheckAuth(userName,password)
		if userInfo.ID >0 {
			token,err := util.CreateToken(userInfo.ID, userInfo.Username)
			if err != nil {
				code = e.ERROR_AUTH_TOKEN
			} else {
				data["token"] = token
				code = e.SUCCESS
			}
		} else {
			code = e.ERROR_NO_USER
		}
	} else {
		msg = e.GetValidMsg(valid)
	}
	response.ApiReturn(c, code, data, msg)
}
